#include "list.h"

void initSqList(SqList& slist)
{
    slist.elem=(Elem*)malloc(SqList_INIT_SIZE*sizeof(Elem));

    if(!slist.elem)
    {
        exit(OVERFLOW);
    }
    slist.length=0;
    slist.listsize=SqList_INIT_SIZE;
}
void destorySqList(SqList& slist)
{
    free(slist.elem);
    slist.length=0;
    slist.listsize=0;
}
void clearSqList(SqList& slist)
{
    slist.length=0;
}
bool SqListEmpty(const SqList& slist)
{
    if( slist.length == 0){
        return true;
    }else{
        return false;
    }
}
size_t SqListLengh(const SqList& slist)
{
    return slist.length;
}
bool getElem(const SqList& slist,size_t index,Elem& e)
{
    if( index<1 || index > slist.length )
    {
        return false;
    }
    e = *(slist.elem+index-1);
    return true;
}
size_t locateElem(const SqList& slist,const Elem& elem,bool (*compare)(const Elem&,const Elem&))
{
    Elem* ptr=slist.elem;
    size_t i=0;
    while(i<slist.length)
    {
        if(compare(*ptr++,elem))
        {
            return i+1;
        }
        ++i;
    }
    return 0;
}
bool priorElem(SqList& slist,const Elem& e,Elem* out)
{
    size_t i=2;
    Elem *p=slist.elem+1;
    while(i<=slist.length&& *p!=e)
    {
        ++i;
        ++p;
    }
    if(i>slist.length){
        return false;
    }else{
        *out=*--p;
        return true;
    }
}
bool nextElem(SqList& slist,const Elem& e,Elem* out)
{
    size_t i=1;
   Elem *p=slist.elem;
   while(i<slist.length&&*p!=e)
   {
     i++;
     p++;
   }
   if(i==slist.length)
   {
     return false;
   }
   else
   {
     *out=*++p;
     return true;
   }
}
bool insertElem(SqList&,size_t,const Elem&);
bool deleteElem(SqList&,size_t,Elem&);
void SqListTraverse(const SqList&,void (*visit)(const Elem&));
